package com.xhsj.user.security.config;

import com.xhsj.user.security.entity.LoginUser;
import com.xhsj.user.security.filter.IntegrationAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenStore;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description AuthorizationServerConfig
 * @Author suxiaolin
 * @Date 2020/8/27 9:40
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    /**
     * 认证管理器
     *
     * @see SecurityConfig 的authenticationManagerBean()
     */
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private RedisConnectionFactory redisConnectionFactory;
    @Autowired
    private IntegrationAuthenticationFilter integrationAuthenticationFilter;


    /**
     * 令牌存储
     */
    @Bean
    public TokenStore tokenStore() {
        // 基于redis存储
        MyRedisTokenStore redisTokenStore = new MyRedisTokenStore(redisConnectionFactory);
        return redisTokenStore;
        // 基于内存
//        return new InMemoryTokenStore();
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager);
        endpoints.tokenStore(tokenStore());
        endpoints.reuseRefreshTokens(false); //该字段设置设置refresh token是否重复使用,true:reuse;false:no reuse.
        endpoints.tokenEnhancer((accessToken, authentication) -> {
            addLoginUserInfo(accessToken, authentication);
            return accessToken;
        });
//        endpoints.accessTokenConverter(accessTokenConverter());

    }

    /**
     * 将当前用户信息追加到登陆后返回的json数据里<br>
     * 通过参数access_token.add-userinfo控制<br>
     * 2018.07.13
     *
     * @param accessToken
     * @param authentication
     */
    private void addLoginUserInfo(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        if (accessToken instanceof DefaultOAuth2AccessToken) {
            DefaultOAuth2AccessToken defaultOAuth2AccessToken = (DefaultOAuth2AccessToken) accessToken;

            Authentication userAuthentication = authentication.getUserAuthentication();
            Object principal = userAuthentication.getPrincipal();
            if (principal instanceof LoginUser) {
                LoginUser loginUser = (LoginUser) principal;

                Map<String, Object> map = new HashMap<>(defaultOAuth2AccessToken.getAdditionalInformation()); // 旧的附加参数
                map.put("fullName", loginUser.getFullName()); // 追加当前登陆用户
                map.put("edfghj", "852"); // 追加当前登陆用户
                map.put("userId", loginUser.getUserId()); // 追加当前登陆用户

                defaultOAuth2AccessToken.setAdditionalInformation(map);
            }
        }
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.allowFormAuthenticationForClients(); // 允许表单形式的认证
        security.addTokenEndpointAuthenticationFilter(integrationAuthenticationFilter);
    }


    /**
     * #### 配置客户端详情 ####
     * 我们将client信息存储到oauth_client_details表里<br>
     * 并将数据缓存到redis
     *
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()//基于内存存放
                .withClient("system")
                .secret(passwordEncoder.encode("system"))
                .authorizedGrantTypes("authorization_code", "client_credentials", "refresh_token","password", "implicit")//客户端可以使用的授权方式
                .scopes("app")
                .accessTokenValiditySeconds(60*60*24*7)//设置token验证时间
                .refreshTokenValiditySeconds(60*60*24*7)//设置token刷新时间
        ;

    }


}

